package yueyong.salarymanagement.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.util.Strings;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TreeMap;


/**
 * Copyright: yueyong (c) 2022
 *
 * @author he.shaorong
 * @version 1.0
 * @date 2022/2/6
 */
public class SendShortMessageUtil {
    public static final String TIMESTAMP = "https://api.mysubmail.com/service/timestamp";
    private static final String URL = "https://api.mysubmail.com/message/send";
    public static final String TYPE_MD5 = "md5";
    public static final String TYPE_SHA1 = "sha1";

    private static final String module = "【工资条】%s，工作辛苦了，请点击%s查看您在%s的%s工资明细，您也可以直接关注微信公众号“悦用工资条”查看。";

    private static final String LINK_URL = "https://i.postimg.cc/6Qf7Z3Xw/20220206143749.jpg";

    private static final String VERIFY_CODE_MODULE = "【悦用工资条】验证码：%d, 5分钟内有效, 请勿泄露。";

    public static Pair<Boolean, String> sendShortMessage(String content, String phoneNumber) {
        TreeMap<String, String> requestData = new TreeMap<String, String>();
        String appid = "72553";
        String appkey = "2bea3c3c0384e833f226e8ef9a43d5ea";
        String to = phoneNumber;
        String sign_type = "md5";
        String sign_version = "2";

        //组合请求数据
        requestData.put("appid", appid);
        requestData.put("to", to);
        if (sign_type.equals(TYPE_MD5) || sign_type.equals(TYPE_SHA1)) {
            String timestamp = getTimestamp();
            requestData.put("timestamp", timestamp);
            requestData.put("sign_type", sign_type);
            requestData.put("sign_version", sign_version);
            String signStr = appid + appkey + RequestEncoder.formatRequest(requestData) + appid + appkey;
            System.out.println(signStr);
            requestData.put("signature", RequestEncoder.encode(sign_type, signStr));
        } else {
            requestData.put("signature", appkey);
        }
        requestData.put("content", content);
        //post请求
        HttpPost httpPost = new HttpPost(URL);
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-Type", "application/json");
        StringEntity entity = new StringEntity(JSONObject.toJSONString(requestData), "UTF-8");
        httpPost.setEntity(entity);
        try {
            CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build();
            HttpResponse response = closeableHttpClient.execute(httpPost);
            HttpEntity httpEntity = response.getEntity();
            if (httpEntity != null) {
                //解析错误码
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    return Pair.of(true, "ok");
                } else if (response.getStatusLine().getStatusCode() == 115) {
                    return Pair.of(false, "该手机号码请求超限");
                } else if (response.getStatusLine().getStatusCode() == 202) {
                    return Pair.of(false, "错误的收件人地址");
                } else if (response.getStatusLine().getStatusCode() == 203) {
                    return Pair.of(false, "你所标记的地址薄不包含任何联系人");
                } else if (response.getStatusLine().getStatusCode() == 251) {
                    return Pair.of(false, "错误的收件人地址");
                } else if (response.getStatusLine().getStatusCode() == 252) {
                    return Pair.of(false, "你所标记的地址薄不包含任何联系人");
                } else if (response.getStatusLine().getStatusCode() == 253) {
                    return Pair.of(false, "此联系人已退订你的短信系统。");
                } else if (response.getStatusLine().getStatusCode() == 501) {
                    return Pair.of(false, "错误的目标地址簿标识");
                } else if (response.getStatusLine().getStatusCode() == 901 ||
                        response.getStatusLine().getStatusCode() == 903 ||
                        response.getStatusLine().getStatusCode() == 904 ||
                        response.getStatusLine().getStatusCode() == 905) {
                    return Pair.of(false, "账户余额已用尽");
                } else {
                    return Pair.of(false, "send short message error");
                }
            } else {
                return Pair.of(false, "send short message error");
            }
        } catch (ClientProtocolException cpe) {
            return Pair.of(false, cpe.getMessage());
        } catch (IOException ioe) {
            return Pair.of(false, ioe.getMessage());
        }
    }

    public static String buildShortMessageContent(String companyName, String url, String name, Date payDate) {
        DateFormat bf = new SimpleDateFormat("yyyy年MM月");
        String dateStr = bf.format(payDate);

        if(Strings.isNotBlank(url)) {
            return String.format(module, name, url, companyName, dateStr);
        }
        return String.format(module, name, LINK_URL, companyName, dateStr);
    }

    public static String buildVerifyMessage(long verifyCode) {
        return String.format(VERIFY_CODE_MODULE, verifyCode);
    }


    //获取时间戳
    private static String getTimestamp() {
        CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build();
        HttpGet httpget = new HttpGet(TIMESTAMP);
        try {
            HttpResponse response = closeableHttpClient.execute(httpget);
            HttpEntity httpEntity = response.getEntity();
            String jsonStr = EntityUtils.toString(httpEntity, "UTF-8");
            if (jsonStr != null) {
                JSONObject json = JSONObject.parseObject(jsonStr);
                return json.getString("timestamp");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
